<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<!--  <meta http-equiv="Access-Control-Allow-Origin" content="*" />-->
  <title id="biaoti">xterm.js</title>
  <script src="js/jquery.js" type="text/javascript"></script>

  <script src="js/index/websshSSHRestart.js" type="text/javascript"></script>
  <script src="js/index/websshMonitor.js" type="text/javascript"></script>

  <script src="js/jquery-cookie.js" type="text/javascript"></script>
  <link rel="stylesheet" href="css/xterm.css">
  <script src="js/xterm.js"></script>
  <style>
    #terminal{
      box-shadow: 2px 2px 2px #d2cbcb;
    }
    body{
      overflow: hidden;
    }
    .monitor{
      width: 1.2vw;
      top: 0.4vh;
      position: relative;
    }
  </style>
  <script>
    <!--  获取地址栏参数-->
    var loc=location.href;
    var n2=loc.indexOf('=');
    var n1=loc.length;
    var str=loc.slice(n2+1,n1);
    var aryStr=str.split('@');
    var strPat=aryStr[1].split('=')[1];
    ip=aryStr[0]
    $("#biaoti").text(ip);
    apiport=strPat
    outport=aryStr[2].split('=')[1]
    user=aryStr[3].split('=')[1]
    name=aryStr[4].split('=')[1]
    name = decodeURIComponent(name)

    // 屏蔽F5刷新
    function f_DisableF5Refresh(event) {
      var e = event || window.event;
      var keyCode = e.keyCode || e.which;
      if(keyCode === 116) {
        if(e.preventDefault) { //非IE
          e.preventDefault();
        } else { //IE
          e.keyCode = 0;
          e.returnValue = false;
        }
      }else if(keyCode === 82){
        if(e.preventDefault) { //非IE
          e.preventDefault();
        } else { //IE
          e.keyCode = 0;
          e.returnValue = false;
        }
      }
    }
    if(document.addEventListener) {
      document.addEventListener('keydown', f_DisableF5Refresh, false);
    } else {
      document.attachEvent('onkeydown', f_DisableF5Refresh);
    }
  </script>
</head>

<!-- 发送两个回车进行端口9999连接 -->
<body onload="print(outport);sendBegin('\r',apiport);print(outport);" style="background-color: #FFF;color: #000;padding: 0;margin: 0;">
<div id="terminal"></div>

<div id="sshMonitor" style="height: 3vh;width: 50vw;position: relative;top: 0;right: 0vw;font-size: 10px;user-select: none;"></div>

<script>
  <!-- 屏幕大小 -->
  window_width = window.screen.width;
  window_height = window.screen.height;
  console.info("列数："+Math.floor(window_width/11))
  let term = new Terminal({
    rows: Math.floor(window_height/29),
    cols: Math.floor(window_width/13),
    rendererType: 'canvas', //,dom
    fontSize: 18,
    fontWeight: '250', //字体加粗
    convertEol: true,
    fontFamily: `'DejaVu Sans Mono','Fira Mono', monospace`,
    cursorStyle: 'underline', //光标样式 bar、underline、block
    useStyle:true,
    rightClickSelectsWord: true,
    scrollback: 9000,
    cursorBlink: true, // 光标闪烁
    disableStdin: false, //是否应禁用输入。
    bellStyle: 'sound', //终端响铃
    // allowProposedApi:true,
    // rightClickSelectsWord: true,
    //logLevel: 'debug', //日志等级
    // bellSound?: string; // 当 bellStyle='sound' 时，用于 sound 的数据URI
    // lineHeight: 26 //行高
    //letterSpacing: 100 //字符间距
    // cursor: 'help',//设置光标
    // convertEol: False, //启用时，光标将设置为下一行的开头
    // tabStopWidth: 4, //终端中制表位的大小
    // cursorWidth: 10px //光标宽度
    // allowTransparency: true,
    theme: {
      foreground: '#000', //字体
      selection: '#AAAAAA49',//文字选中背景颜色
      background: '#FFF', //背景色
      cursor: 'black', //光标颜色
      cursorAccent: '#000', //光标强调色
    }
  });

  term.open(document.getElementById('terminal'));
  // 2022年11月11日 解决切换终端后没有焦点问题 haha 历时两个多月
  setInterval(
          function (){
            // 如果添加主机界面或ftp界面显示状态，则失去终端焦点（获取父界面元素）
            if ($("#sftpwindow",window.parent.document).is(':visible') || $("#addSSH",window.parent.document).is('.addSSH')) {
              term.blur(); //终端失去焦点
            }else {
              term.focus();
            }
          },1
  );

  //发送函数
  function send(c,apiport) {
    $.post(
            "http://127.0.0.1:"+apiport+"/jaina", {
              // "monitor":0,
              "cmd": c
            },function (data){
              console.log("接口消息 ：",data)
            }
    ).fail(function (){
      restartSSH(ip,user,name,apiport,outport,term);
    });
    console.log("发送命令 : "+c);
    return true;
  }
  // 终端初始化 发送函数
  function sendBegin(c,apiport) {
    console.log("命令端口：" + apiport)
    $.post(
            "http://127.0.0.1:"+apiport+"/jaina", {
              // "monitor":0,
              "cmd": c
            }
    );
  }

  //输出函数
  function print(outport) {
    console.log("输出端口：" + outport)
    var status =outport-1;
    console.log("状态端口：" + status)
    var socket = new WebSocket('ws://127.0.0.1:'+outport)
    socket.onopen = function () {
      console.log(outport + "连接成功!")
      // 设置终端宽度和空格前缀屏蔽历史记录（针对于本次连接）
      sendBegin("stty cols "+Math.floor(window_width/13) + ";history -c" + "\r",apiport)
      sendBegin("HISTCONTROL=ignorespace" + ";history -c" + "\r",apiport)

      //监控
      setInterval(function (){
        websshMonitor(ip,user,name,apiport)
      },5000);
    };
    socket.onmessage = function(event) {
      term.write(event.data);
      console.log(`接收消息 : ${event.data}`);
      if ( event.data === "") {
        restartSSH(ip,user,name,apiport,outport,term);
      }
    };
    socket.onclose = function () {
      console.info("输出端口关闭！")
    };
  }

  // let lastTime;
  function runFakeTerminal() {
    if (term._initialized) {
      return;
    }
    term._initialized = true;

    //单独一行
    term.writeln("Welcome to xterm.js");

    //你只管发送按键，剩下的交给终端
    term.onData( function (key) {
      var reg=/^[\u4E00-\u9FA5]+$/;
      // 不全是中文
      if (!reg.test(key)){
          send(key,apiport)
          return false ;
       }else{ // 是中文
          send(key,apiport)
          return true ;
       }
    });
    term.onKey(e => {
      // Ctrl + V
      if (e.domEvent.keyCode === 86 && e.domEvent.ctrlKey){
        navigator.clipboard
                .readText()
                .then((v) => {
                  // console.log("获取剪贴板成功：", v);
                  send(v,apiport)
                })
                .catch((v) => {
                  console.log("获取剪贴板失败: ", v);
                });
      }else if(e.domEvent.ctrlKey && e.domEvent.keyCode === 68) { // Ctrl + D
        // 2022年9月13日 在终端中退出容器也会提示
        // alert("可以右击顶部标签退出终端!")
      }else if(e.domEvent.ctrlKey && e.domEvent.keyCode === 37) { // Ctrl + left
        $.cookie("toggle", "left", { expires: 7 ,path: '/'});
      }else if(e.domEvent.ctrlKey && e.domEvent.keyCode === 39) { // Ctrl + right
        $.cookie("toggle", "right", { expires: 7 ,path: '/'});
      // Ctrl + F1 重新连接
      }else if (e.domEvent.ctrlKey && e.domEvent.keyCode === 112){
        restartSSH(ip,user,name,apiport,outport,term);
      }
    });
  }

  runFakeTerminal();
  print(outport)

  // 鼠标左键选中既复制
  var container = container ||  document;
  container.onmouseup = function(){
    copy = window.getSelection();
    document.execCommand('copy');
  }

  // 鼠标右击事件 复制和粘贴
  document.oncontextmenu = function () {
    navigator.clipboard
              .readText()
              .then((v) => {
                console.log("获取剪贴板成功：", v);
                send(v,apiport)
              })
              .catch((v) => {
                console.log("获取剪贴板失败: ", v);
              });
    // 右键复制后清除字符选中状态
    term.clearSelection()
    return false; //阻止浏览器的右击菜单
  };

  // 切换终端操作
  $('body').keydown(
          function (e){
            if(e.ctrlKey && e.keyCode === 37) { // Ctrl + left
              $.cookie("toggle", "left", { expires: 7 ,path: '/'});
            }else if(e.ctrlKey && e.keyCode === 39) { // Ctrl + right
              $.cookie("toggle", "right", { expires: 7 ,path: '/'});
            }
          }
  );
</script>
</body>
</html>